import 'dart:convert';

import 'package:fish_redux/fish_redux.dart';
import '../../../app_files.dart';
import 'dart:convert' as convert;
import 'dart:io';
import '../../FixOrderView/fix_result_page/state.dart';
import 'action.dart';
import 'state.dart';

Effect<EngineerResultViewState> buildEffect() {
  return combineEffects(<Object, Effect<EngineerResultViewState>>{
    Lifecycle.initState: _initState,
    EngineerResultViewAction.onTapResultPic: _onTapResultPic,
    EngineerResultViewAction.onTapResultPic2: _onTapResultPic2,
    EngineerResultViewAction.onTapAddPic: _onTapAddPic,
    EngineerResultViewAction.onTapPic: _onTapPic,
    EngineerResultViewAction.onTapSign: _onTapSign,
    EngineerResultViewAction.onSubmit: _onSubmit,
    EngineerResultViewAction.onSave: _onSave,
  });
}

void _initState(Action action, Context<EngineerResultViewState> ctx) async {
  if (ctx.state.isDetail) {
    ResultData res =
    await CommonNetWork.fixOrderDetail(ctx.state.itemModel.itemID);
    if (res.success) {
      FixResultModel model = FixResultModel.fromJson(res.data['data']);
      String dispatchLog = CommonUtils.checkNullToString(res.data['data']['bizDispatchlog']);
      if (dispatchLog.isNotEmpty) {
        ctx.state.logList = jsonDecode(dispatchLog);
      }
      ctx.state.model = model;
      ctx.state.isLoad = true;
      ctx.dispatch(EngineerResultViewActionCreator.onAction());
    } else {

      await CommonUtils.showAlertView(ctx.context, res.desc);
      Navigator.pop(ctx.context);
    }
  }
}

void _onTapResultPic(Action action, Context<EngineerResultViewState> ctx) async {
  var file = action.payload;
  await CommonUtils.showMediaAlbumView(
    ctx.context,
    initialIndex: ctx.state.model.repairPhotos.indexOf(file),
    files:  ctx.state.model.repairPhotos,
  );
}

void _onTapResultPic2(Action action, Context<EngineerResultViewState> ctx) async {
  var file = action.payload;
  await CommonUtils.showMediaAlbumView(
    ctx.context,
    initialIndex: ctx.state.model.beforePhotos.indexOf(file),
    files:  ctx.state.model.beforePhotos,
  );
}

void _onTapAddPic(Action action, Context<EngineerResultViewState> ctx) async {
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,type: 2,info: ctx.state.itemModel);
  if (imgFile != null) {
    ctx.state.model.orderPhoto.add(imgFile);
    ctx.dispatch(EngineerResultViewActionCreator.onAction());
  }
}

void _onTapPic(Action action, Context<EngineerResultViewState> ctx) async {
  pushPhoto(file) async {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex: ctx.state.model.orderPhoto.indexOf(file),
      files:  ctx.state.model.orderPhoto,
    );
  }

  var file = action.payload;
  if (ctx.state.isDetail) {
    pushPhoto(file);
  } else {
    int res =
    await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      ctx.state.model.orderPhoto.remove(file);
      ctx.dispatch(EngineerResultViewActionCreator.onAction());
    } else if (res == 0) {
      pushPhoto(file);
    }
  }
}

void _onTapSign(Action action, Context<EngineerResultViewState> ctx) async {
  if (ctx.state.isDetail) {
    List<GalleryExampleItem> items = [
      GalleryExampleItem(
        id: '0',
        resource: ctx.state.model.signPhoto,
      )
    ];
    items = await CommonUtils.showPhotoAlbumView(
      ctx.context,
      initialIndex: 0,
      galleryItems: items,
    );
  } else {
    var res = await CommonUtils.showActionSheet(ctx.context, button: ['修改']);
    if (res == 0) {
      var file =
      await CommonUtils.pushRoute(ctx.context, RoutePath.orderSignView);
      if (file != null) {
        ctx.state.model.signPhoto = file;
        ctx.dispatch(EngineerResultViewActionCreator.onAction());
      }
    }
  }
}


void _onSave(Action action, Context<EngineerResultViewState> ctx) async {
  CommonUtils.showWaitLoading(ctx.context, descText: '上传图片中');
  List<String> orderPhoto = [];
  if (ctx.state.model.orderPhoto.isNotEmpty) {
    orderPhoto = await CommonNetWork.multiUploadImgs(ctx.state.model.orderPhoto,
        userNo: ctx.state.itemModel.userNo);
    if (orderPhoto == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
  }
  String signPhoto = '';
  if (ctx.state.model.signPhoto != null) {
    List<String> items =  await CommonNetWork.multiUploadImgs([ctx.state.model.signPhoto],
        userNo: ctx.state.itemModel.userNo);
    if (items == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
    signPhoto = items.first;
  }
  List<String> uploads = await CommonNetWork.multiUploadImgs(
      ctx.state.model.repairPhotos,
      userNo: ctx.state.itemModel.userNo);
  if (uploads == null) {
    Navigator.pop(ctx.context);
    CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
    return;
  }
  List<String> before = await CommonNetWork.multiUploadImgs(
      ctx.state.model.beforePhotos,
      userNo: ctx.state.itemModel.userNo);
  if (before == null) {
    Navigator.pop(ctx.context);
    CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
    return;
  }
  String json = convert.jsonEncode({
    'RepairPhotos': uploads,
    'RepairContent': ctx.state.model.repairContent,
    'BeforePhotos': before,
    'BeforeContent': ctx.state.model.beforeContent,
  });
  Navigator.pop(ctx.context);
  CommonUtils.showWaitLoading(ctx.context, descText: '正在提交中');
  ResultData res = await CommonNetWork.fixOrderSubmit(
    orderPhoto: orderPhoto.join(','),
    jsonContent: json,
    signPhoto: signPhoto,
    isSolve: ctx.state.model.isSolve,
    itemID: ctx.state.itemModel.itemID,
    isSave: true,
  );
  Navigator.pop(ctx.context);
  if (res.success) {
    bus.emit('refreshList');
    await CommonUtils.showAlertView(ctx.context, '提交成功');
    Navigator.popUntil(ctx.context, ModalRoute.withName('/'));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}


void _onSubmit(Action action, Context<EngineerResultViewState> ctx) async {
  bool isSave = action.payload;
  if (ctx.state.model.signPhoto == null) {
    var res = await CommonUtils.pushRoute(ctx.context, RoutePath.orderSignView);
    if (res != null) {
      ctx.state.model.signPhoto = res;
      ctx.dispatch(EngineerResultViewActionCreator.onAction());
    }
  } else {
    if (ctx.state.model.isSolve == null && !isSave) {
      CommonUtils.showErrorInfo(ctx.context, '请选择报装结果');
      return;
    }
    if (ctx.state.model.orderPhoto.length == 0) {
      CommonUtils.showErrorInfo(ctx.context, '请拍照留存');
      return;
    }

    CommonUtils.showWaitLoading(ctx.context, descText: '上传图片中');

    List<String> uploads = await CommonNetWork.multiUploadImgs(
        ctx.state.model.repairPhotos,
        userNo: ctx.state.itemModel.userNo);
    if (uploads == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
    List<String> before = await CommonNetWork.multiUploadImgs(
        ctx.state.model.beforePhotos,
        userNo: ctx.state.itemModel.userNo);
    if (before == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
    String json = convert.jsonEncode({
      'RepairPhotos': uploads,
      'RepairContent': ctx.state.model.repairContent,
      'BeforePhotos': before,
      'BeforeContent': ctx.state.model.beforeContent,
    });
    print(json);

    List img = [];
    img.addAll(ctx.state.model.orderPhoto);
    img.add(ctx.state.model.signPhoto);

    List<String> images = await CommonNetWork.multiUploadImgs(img,
        userNo: ctx.state.itemModel.userNo);
    if (images == null) {
      Navigator.pop(ctx.context);
      CommonUtils.showErrorInfo(ctx.context, '上传图片失败，请重新上传');
      return;
    }
    List<String> orderPhoto = images.sublist(0, images.length - 1);

    Navigator.pop(ctx.context);
    CommonUtils.showWaitLoading(ctx.context, descText: '正在提交中');
    ResultData res = await CommonNetWork.fixOrderSubmit(
      orderPhoto: orderPhoto.join(','),
      jsonContent: json,
      signPhoto: images.last,
      isSolve: ctx.state.model.isSolve,
      itemID: ctx.state.itemModel.itemID,
      isSave: isSave,
    );
    Navigator.pop(ctx.context);
    if (res.success) {
      bus.emit('refreshList');
      await CommonUtils.showAlertView(ctx.context, '提交成功');
      Navigator.popUntil(ctx.context, ModalRoute.withName('/'));
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
  }
}